module RdialogHelper

  # create rdialog html tags and make it a popup object,
  # See README for detailed usage.
  def rdialog(id, options = {}, &block) 

    script = rdialog_script(id, options) 

    if block_given?
      content = rdialog_tag(id, &block)
      concat(script, block.binding)
    else
      content = "<div id='#{id}' style='display:none' class='rdlg'></div>"
      content + " " + script
    end
  end

  # create only the rdialog 
  def rdialog_tag(id, &block) 
    if block_given?
      content = capture(&block)
      concat("<div id='#{id}' style='display:none' class='rdlg'>", block.binding)
      concat(content, block.binding)
      concat("</div>", block.binding)
    else
      "<div id='#{id}' style='display:none' class='rdlg'></div>"
    end
  end


  # javascript tag to construct fully framed dialog
  # and make it an popup object
  def rdialog_script(id, options= {})
    options[:title]  ||= 'Dialog'
    options[:width]  ||= 'null'
    options[:opener] ||= 'null'

    options[:modal]  ||= true
    options[:duration]  ||= 1
    options[:draghandle] ||= 'rdlg-hdr-center'


    script = %{
       rdlg_create("#{id}", "#{options[:title]}", #{options[:width]});
       new Popup("#{id}", "#{options[:opener]}",
         {modal:#{options[:modal]}, duration:#{options[:duration]},
           draghandle:#{"'"+options[:draghandle]+"'"},
           closebox:'rdlg-close' }); }


    javascript_tag script
  end

  # javascript tag to change title or width of dialog
  def rdialog_config(id, options= {})
    options[:title]  ||= 'Dialog'
    options[:width]  ||= 'null'

    javascript_tag %{rdlg_config("#{id}", "#{options[:title]}", #{options[:width]})}
  end
end
